<template>
  <el-dialog
    class="assign-role"
    title="分配角色"
    :visible="showRoleDialog"
    @close="handleCloseDialog"
    @open="handleOpenDialog"
  >
    <!-- 这里准备复选框 -->
    <template>
      <el-checkbox-group v-model="roleIds" v-loading="loading">
        <el-checkbox
          v-for="item in list"
          :key="item.id"
          :label="item.id"
        >
          {{ item.name }}
        </el-checkbox>
      </el-checkbox-group>
    </template>

    <template #footer>
      <el-button type="primary" size="small" @click="clickAssignRoles">确定</el-button>
      <el-button size="small" @click="handleCloseDialog">取消</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { reqGetRoleList } from '@/api/setting'
import { reqGetUserDetailById, reqAssignRoles } from '@/api/employees'

export default {
  props: {
    showRoleDialog: {
      type: Boolean,
      default: false
    },
    // 用户的id 用来查询当前用户的角色信息
    userId: {
      type: String,
      default: null
    }
  },

  data() {
    return {
      list: [], // 数组，存储所有的角色
      roleIds: [], // 数组，存储提交给后台的选中的项的id
      loading: false // 加载效果
    }
  },

  methods: {
    // 打开弹层
    async handleOpenDialog() {
      this.loading = true
      Promise.all([this.getRoleList(), this.getUserDetailById()]).then(value => {
        this.loading = false
      })
    },

    // 获取角色列表
    async getRoleList() {
      const { data: { rows }} = await reqGetRoleList(1, 9999)
      this.list = rows
    },

    // 获取员工基本信息
    async getUserDetailById() {
      const { data: { roleIds }} = await reqGetUserDetailById(this.userId)
      this.roleIds = roleIds
    },

    // 关闭弹层
    handleCloseDialog() {
      this.$emit('update:showRoleDialog', false)
      this.roleIds = []
    },

    // 分配角色
    async clickAssignRoles() {
      await reqAssignRoles(this.userId, this.roleIds)
      this.$message.success('分配成功')
      this.handleCloseDialog()
    }
  }
}
</script>

<style lang="scss" scoped>
.assign-role {
  ::v-deep {
    .el-checkbox {
      font-size: 30px;
    }
  }
}
</style>
